package com.hoopchina.weibo;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.URL;

import com.hoopchina.weibo.http.ImageItem;

import android.content.Context;

/**
 * 
 * @author neusoft
 *
 */
public class WeiboUtils {
    // 设置图片的缓冲区
    private static final int IO_BUFFER_SIZE = 4 * 1024;
    public static ImageItem GetImageItem(String url) {
    	if( url.equals("") )
    		return null;
        InputStream in = null;
        ImageItem imageItem = null;
        BufferedOutputStream out = null;
        try {
            in = new BufferedInputStream(new URL(url).openStream(),
                    IO_BUFFER_SIZE);
            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
            copy(in, out);
            out.flush();
            byte[] data = dataStream.toByteArray();
            imageItem = new ImageItem(data);
            return imageItem;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public static File GetFile(Context context,String url) {
        String extendName = url.substring(url.lastIndexOf(".") + 1);
        InputStream in = null;
        BufferedOutputStream out = null;
        try {
            in = new BufferedInputStream(new URL(url).openStream(),
                    IO_BUFFER_SIZE);
            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
            copy(in, out);
            out.flush();
            byte[] data = dataStream.toByteArray();
            File tmpFile = new File(context.getCacheDir() + "/BindImages", "temp."
            	    + extendName);
            RandomAccessFile finalFile = new RandomAccessFile(tmpFile, "rwd");
            finalFile.write(data);
            finalFile.close();
            return tmpFile;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    private static void copy(InputStream in, OutputStream out)
        throws IOException {
        byte[] b = new byte[IO_BUFFER_SIZE];
        int read;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
    }    
}